package com.xca.znb.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.Toast;
import android.util.Base64;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.xca.znb.R;
import com.xca.znb.entity.Collect;
import com.xca.znb.entity.News;
import com.xca.znb.entity.User;
import com.xca.znb.model.impl.ShowNewsImpl;
import com.xca.znb.presenter.ShowNewsPresenter;

import java.io.ByteArrayOutputStream;

public class SchoolShowNews extends AppCompatActivity {
    private ImageView  back  ;
    private CheckBox addCollection ;
    private WebView showNews ;
    private ShowNewsPresenter presenter ;
    @SuppressLint({"MissingInflatedId", "WrongViewCast", "SetJavaScriptEnabled"})
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.show_news);
        back = findViewById(R.id.show_news_back) ;
        addCollection = findViewById(R.id.show_news_add_collection);
        showNews = findViewById(R.id.show_news_message) ;

        ShowNewsImpl showNews1 = new ShowNewsImpl(this) ;
        presenter = new ShowNewsPresenter(showNews1);

        String type = "news" ;//收藏类型
        SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString("phone" , "");//收藏user

        Intent intent = getIntent();
        String getNewsId = intent.getStringExtra("schoolFragment_showNews");


        try {

            // 确保getNewsId是一个有效的字符串表达形式的整数
            int newsId = Integer.parseInt(getNewsId);

            // 获取新闻和发布者信息
            News news = presenter.getNewsById(newsId);
            User user = presenter.getUserByPhone(news.getPublisher());

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // 配置WebView设置以便更好地显示HTML内容
                    WebSettings webSettings = showNews.getSettings();
                    webSettings.setJavaScriptEnabled(true); // 允许JavaScript执行
                    webSettings.setLoadWithOverviewMode(true); // 适应屏幕宽度缩放
                    webSettings.setUseWideViewPort(true); // 支持viewport标签来适应不同屏幕
                    webSettings.setLoadsImagesAutomatically(true); // 自动加载图片

                    // 构建HTML内容字符串，假设buildHtml方法已正确定义
                    String htmlContent = buildHtml(news, user);

                    // 加载自定义的HTML内容到WebView
                    showNews.loadDataWithBaseURL(null, htmlContent, "text/html", "utf-8", null);
                }
            });

        } catch (NumberFormatException e) {
            // 如果getNewsId不是有效的整数格式，处理异常
            // 可能需要添加一些逻辑来处理这种情况，比如显示错误消息给用户
            e.printStackTrace(); // 打印堆栈跟踪，实际开发中可能需要更友好的错误处理
        }

        addCollection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Collect collect = presenter.getCollect(getNewsId , type , phone);
                if (addCollection.isChecked()){
                    if (collect == null){
                        presenter.addCollect(getNewsId , type , phone);
                        Collect collect1 = presenter.getCollect(getNewsId , type , phone) ;
                        if (collect1 != null){
                            Toast.makeText(SchoolShowNews.this, "收藏成功", Toast.LENGTH_SHORT).show();
                        }
                    }
                }else {
                    if (collect != null){
                        presenter.delCollect(collect.getId());
                        Collect collect1 = presenter.getCollect(getNewsId , type , phone) ;
                        if (collect1 == null){
                            Toast.makeText(SchoolShowNews.this, "取消收藏", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
        });


        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }


    @SuppressLint("SuspiciousIndentation")
    private String buildHtml(News news , User user) {
        StringBuilder htmlBuilder = new StringBuilder();
            htmlBuilder.append("<html><head><style>")
                    .append("body {\n" +
                            "            font-family: Arial, sans-serif;\n" +
                            "            line-height: 1.6;\n" +
                            "        }\n" +
                            "        .header {\n" +
                            "            text-align: center;\n" +
                            "            margin-bottom: 20px;\n" +
                            "            font-size: 35px;\n" +
                            "        }\n" +
                            "        .sub-header {\n" +
                            "            color: #666;\n" +
                            "            margin-bottom: 10px;\n" +
                            "            font-size: 50px;" +
                            "        }\n" +
                            "        .metadata {\n" +
                            "            color: #999;\n" +
                            "            text-align: right;\n" +
                            "            margin-bottom: 10px;\n" +
                            "            font-size: 35px;" +
                            "        }\n" +
                            "        img {\n" +
                            "            max-width: 100%;\n" +
                            "            height: 450px;\n" +
                            "            display: block;\n" +
                            "            margin: 0 auto;\n" +
                            "            margin-bottom: 20px;\n" +
                            "        }\n" +
                            "        .article-content {\n" +
                            "            text-align: justify;\n" +
                            "            font-size: 45px;" +
                            "        }\n" +
                            "    </style>\n" +
                            "</head>")
                    .append("<body>")
                    .append("<div class='header'><h1>").append(news.getFirstTitle()).append("</h1></div>")
                    .append("<p class='sub-header'>").append(news.getSecondTitle()).append("</p>")
                    .append("<p class='metadata'>发布时间: ").append(news.getTime()).append("</p>");
                    if (user.getName() != null){
                        htmlBuilder.append("<p class='metadata'>").append(" 发布者: ").append(user.getName()).append("</p>");
                    }else {
                        htmlBuilder.append("<p class='metadata'>").append(" 发布者: ").append(news.getPublisher()).append("</p>");
                    }

        if (news.getImg() != null && !news.getImg().isEmpty()) {
            htmlBuilder.append("<img class='image' src='" + encodeImageToBase64(news.getImg()) + "' alt='新闻图片'/>");
        }// 这里添加条件为假时的操作，比如什么都不做 // 图片路径
                    htmlBuilder.append("<div class='article-content'>").append("&nbsp;&nbsp;&nbsp;").append(news.getTexts()).append("</div>")
                    .append("</body></html>");
        return htmlBuilder.toString();
    }

    public String encodeImageToBase64(String imagePath) {
        try {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] imageBytes = baos.toByteArray();
            return "data:image/jpeg;base64," + Base64.encodeToString(imageBytes, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    private void collectData(){
        Intent intent = getIntent();
        String gId = intent.getStringExtra("schoolFragment_showNews");//收藏id
        SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString("phone" , "");//收藏user
        String type = "news" ;

        Collect collect = presenter.getCollect(gId , type , phone) ;
        addCollection.setChecked(collect != null);
    }

    @Override
    protected void onResume() {
        super.onResume();
        collectData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (showNews != null) {
            showNews.clearCache(true);
            showNews.clearHistory();
            showNews.removeAllViews();
            showNews.destroy();
            showNews = null;
        }
    }
}
